from twisted.web.client import getPage
from twisted.python import log



class HonorLister(object):
    """
    An independent honor lister class (because separation of application
    and protocol logic is a good thing).
    """
    triggers = ["!honor","!honour"]
    prefix = "http://wol.swirve.com/players/honor-"
    postfix = ".htm"

    name = "honor"
    help = ["Honor listing:",
            "%c6!honor%c <kingdom#> <island#>"%(03,03)]
    
    def __init__(self, messenger):
        self.messenger = messenger
   
    def command(self, firstword, user, channel, msg):
        parts = msg.split(" ")
        try:
            kd = int(parts[1])
            island = int(parts[2])
        except:
            return {'chanmsg': ["Usage: !honor kingdomnumber islandnumber"]}
        log.msg("User "+user+" in "+channel+" requested honor info on ("+str(kd)+":"+str(island)+").")

        d = self.getHonor(kd, island)
        d.addCallbacks(callback = lambda infos:self.printHonor(channel, infos),
                       errback = lambda _:self.printError(channel))
        return {'chanmsg': ["Looking up ("+str(kd)+":"+str(island)+") provs on the honor list (may take a while)."]}

    def getHonor(self, kd, island):
        d = getPage(self.prefix+str(island)+self.postfix)
        d.addCallbacks(callback = lambda page:(self.parseHonor(page, kd, island)),
                       errback = lambda error:println("Error: ", error))
        return d

    def parseHonor(self, page, kd, island):
        lines = page.splitlines()
        date = "--unknown date--"
        target = "("+str(kd)+":"+str(island)
        honorprovs = []
        for line in lines:
            if line.find("FFEECC>") != -1:
                date = line.split("FFEECC>")[2]
                date = date.split("</FONT><P>")[0]
            
            if line.find(target) != -1:
                prov = line.split("</TH><TD>", 1)[1]
                honor = prov.split("RIGHT>")[1]
                honor = honor.split("</TD>")[0]
                prov = prov.split("</TD><TD>")[0]
                honorprovs.append((honor, prov))
        return (honorprovs, date)
    
    def printHonor(self, channel, infos):
        (honorprovs,date) = infos
        if len(honorprovs) == 0:
            self.messenger(channel, "No provs listed for that kd.")
        for prov in honorprovs:
            self.messenger(channel, prov[0]+" --> "+prov[1])
        self.messenger(channel, "This data was accurate at the beginning of "+date+".")
        
    def printError(self, channel):
        self.messenger(channel, "Error retrieving honor info.")